package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import com.etoak.common.core.vo.PageVO;
import com.etoak.common.web.exception.CustomException;
import com.etoak.entity.Ingredients;
import com.etoak.mapper.IngredientsMapper;
import com.etoak.service.IngredientsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author et2403
 * @since 2024-08-13
 */
@Service
public class IngredientsServiceImpl extends ServiceImpl<IngredientsMapper, Ingredients> implements IngredientsService {

    @Override
    public void add(Ingredients ingredients) {
        /* 校验食材名称 */
        Ingredients savedIngredients = getByName(ingredients.getName());
        if (ObjectUtils.isNotEmpty(savedIngredients)) {
            throw new CustomException("食材名称重复");
        }
        ingredients.setCreateTime(DateUtil.now());
        save(ingredients);
    }

    @Override
    public PageVO<Ingredients> getList(int pageNum, int pageSize, Ingredients ingredients) {
        PageHelper.startPage(pageNum, pageSize);
        List<Ingredients> list = baseMapper.getList(ingredients);
        PageInfo<Ingredients> pageInfo = new PageInfo<>(list);
        return new PageVO<>(pageInfo.getPageNum(), pageInfo.getPageSize(), list, pageInfo.getTotal());
    }

    @Override
    public void update(int id, Ingredients ingredients) {
        /* 验证id */
        if (ObjectUtils.isEmpty(getById(id))) {
            throw new CustomException("食材不存在");
        }
        /* 验证名称是否重复 */
        String name = ingredients.getName();
        if (StringUtils.isNotEmpty(name)) {
            Ingredients saveIngredients = getByName(name);
            if (ObjectUtils.isNotEmpty(saveIngredients) && !saveIngredients.getId().equals(id)) {
                throw new CustomException("食材名称重复了!");
            }
        }
        ingredients.setId(id);
        ingredients.setUpdateTime(DateUtil.now());
        updateById(ingredients);
    }

    @Override
    public void delete(int id) {
        if (ObjectUtils.isEmpty(getById(id))) {
            throw new CustomException("食材不存在!");
        }

        // TODO 判断食材有没有被菜品使用
        removeById(id);
    }

    private Ingredients getByName(String name) {
        return lambdaQuery().eq(Ingredients::getName, name).one();
    }
}
